<?php
session_start();
class MenuController extends Controller
{
   /**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
	public function actionIndex()
	{
      // Check login user
      $user_id = Yii::app()->user->id;
      $action = Yii::app()->request->getParam('action_user','');
      $page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 1; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'ASC'; // Lấy giá trị muốn sắp xếp
      $rowList = array(10,20,30,50,100);
      //Biến xác định phiên làm việc của user
      Yii::app()->session['session_user'] = md5(time());  
      
      if(is_null($user_id))
         $this->redirect('/site/login');
      else{
         
         
         $model = new Menuadmin();
         $list = $model->findAll();
         $total_record = count($list);
         if(!is_numeric($page)) $page = 1;
         if(!is_numeric($limit)) $limit = 10;
         if( $total_record >0 ) {
         	$total_pages = ceil($total_record/$limit);
         } else {
         	$total_pages = 0;
         }
         
         //Khai báo biến cho form tìm kiếm
         $attrbutes_level_1[] = array("menu" => 0);
         $attrbutes_level_2[] = array("menu" => 0);
         $attrbutes_level_3[] = array("menu" => 0);
         $menu_level_1 = array(0 => '-- Nhóm 1 --');
         $menu_level_2 = array(0 => '-- Nhóm 2 --');
         $menu_level_3 = array(0 => '-- Nhóm 3 --');
         $sql =  "SELECT
                  	Menu1,
                     MenuAdminID,
                  	MenuName
                  FROM
                  	menuadmin
                  WHERE
                  	Menu2 = 0";
         $object = $model->findAllBySql($sql);
         
         //Lấy mảng menu level 1
         
         foreach($object as $item){
            $attrbutes_level_1[] = array("menu" => $item["MenuAdminID"]);
            $menu_level_1[$item['MenuAdminID']] = $item['MenuName'];
         }
         
         
         if ($page > $total_pages) $page=$total_pages;
         $start = $limit*$page - $limit; // do not put $limit*($page - 1)
         
         //Nếu người dùng tìm kiếm
         if($action == 'search'){
            if(isset($_POST['Menuadmin'])){
               $model->attributes = $_POST['Menuadmin'];
               
               $where = 'WHERE 1';
               
               if($model->MenuName != ""){ // Tìm kiếm theo từ khóa
                  
                  $where .= " AND MenuName LIKE '%".$model->MenuName."%'";
               }
               $IsActive = $model->IsActive;
               switch($IsActive){ // Tìm kiếm theo trạng thái
                  case 1 : 
                     $where .= ' AND IsActive = 1 ';
                     break;
                  case 0 :
                     $where .= ' AND IsActive = 0 ';
                     break;   
               }
               $menu1 = $model->Menu1;
               $menu2 = $model->Menu2;
               if($menu2 != 0){ // Nếu menu mức 2 được chọn
                  $sql =  "SELECT
                        	a.*
                        FROM
                        	menuadmin a
                        INNER JOIN (
                        	SELECT
                        		MenuAdminID,Menu1,Menu2,Menu3,Menu4
                        	FROM
                        		menuadmin c
                        	WHERE
                        		MenuAdminID = $menu2
                        ) b ON (
                        	b.Menu1 = a.Menu1
                           AND b.menu2 = a.Menu2
                        	AND b.Menu1 > 0
                        	AND b.Menu2 > 0
                        	AND a.Menu3 > 0
                        )
                        $where
                        AND a.MenuAdminID != $menu2";
                  
               }else if($menu1 != 0){
                  $sql =  "SELECT
                           	a.*
                           FROM
                           	menuadmin a
                           INNER JOIN (
                           	SELECT
                           		MenuAdminID,Menu1,Menu2,Menu3,Menu4
                           	FROM
                           		menuadmin c
                           	WHERE
                           		MenuAdminID = $menu1
                           ) b ON (
                           	b.Menu1 = a.Menu1
                              AND b.Menu1 > 0
                           	AND b.Menu2 = 0
                           	AND a.Menu3 = 0
                           )
                           $where
                           AND a.MenuAdminID != $menu1";
               }else{
                  $sql = "SELECT * FROM menuadmin $where ORDER BY $sidx $sord LIMIT $start , $limit";
               }
         }   
         }else{
            $sql = "SELECT * FROM menuadmin ORDER BY $sidx $sord LIMIT $start , $limit";
         }
         
         $object = $model->findAllBySql($sql);
         $list_menu = array();
         foreach($object as $value){
            $list_menu[] = $value->attributes;
         }
         
         $this->render('index',array("model" => $model,
                                     "session_user" => Yii::app()->session['session_user'],
                                     "list" => $list_menu,
                                     "rowList" => $rowList,
                                     "page" => $page,
                                     "start" => $start,
                                     "limit" => $limit,
                                     "sidx" => $sidx,
                                     "sord" => $sord,
                                     "total_record" => $total_record,
                                     "total_pages" => $total_pages,
                                     "menu_level_1" => $menu_level_1,
                                     "menu_level_2" => $menu_level_2,
                                     "menu_level_3" => $menu_level_3,
                                     "attrbutes_level_1" => $attrbutes_level_1,
                                     "attrbutes_level_2" => $attrbutes_level_2,
                                     "attrbutes_level_3" => $attrbutes_level_3
                                     ));
		}
      
      
	}

   
   public function actionCreate(){
      
      $message = '';
      $model = new Menuadmin();
      $all_menu = $model->getAll();
      $tree_menu = $model->getTree($all_menu);
      if(isset($_POST['Menuadmin'])){
         $session_user = Yii::app()->request->getParam('session_user',''); // Biến xác định phiên làm việc của user
         $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
         if($session_user == Yii::app()->session['session_user']){ 
            $model->attributes = $_POST['Menuadmin'];
            if($model->MenuCode == '') $model->MenuCode = CVietnameseTools::makeSearchableStr($model->MenuName);
            $rnd = time().rand(10,99);
            
            if($_FILES['Menuadmin']['name']['MenuImage'] != ''){
               $uploadedFile = CUploadedFile::getInstance($model,'MenuImage');
               $fileName = "{$rnd}-{$uploadedFile}"; 
               $model->MenuImage = $fileName;
            }
            if($model->validate()){
               if($model->save()){
                  if($_FILES['Menuadmin']['name']['MenuImage'] != ''){
                     $pathImage = Yii::app()->basePath.'/../images/menu/'.$fileName;
                     $uploadedFile->saveAs($pathImage);  // image will uplode to rootDirectory/banner/
                     
                     //resize image
                     $image = new SimpleImage();
                     $image->load($pathImage);
                     $image->resizeToWidth(200);
                     $image->save($pathImage);    
                  }
                  
                  
                  $message = 'Thêm mới thành công';
                  
                  
               }
               if($action_user == 'save'){
                  $this->redirect('/index.php/admin/'.$this->id);
               }
            }
         }
      }
      
      $this->layout ='//layouts/cms/create';
      $this->pageTitle = 'Thêm module admin';
      $this->render('create',array('session_user' => Yii::app()->session['session_user'],
                                   'model' => $model,
                                   'message' => $message,
                                   'tree_menu' => $tree_menu,
                                   ));
   }
   
   /**
    * Edit record
   */
   public function actionEdit(){
      
      $session_user = Yii::app()->session['session_user'];
      $id = Yii::app()->request->getParam('id',0);
      $model  = new Menuadmin("update");
      $model->MenuAdminID = $id;
      
      if(isset($_POST['Menuadmin'])){
         $model = Menuadmin::model()->findByPk($_POST['Menuadmin']['MenuAdminID']);
         $model->attributes = $_POST['Menuadmin'];
         $action_user = Yii::app()->request->getParam('action_user');
         if($_FILES['Menuadmin']['name']['MenuImage'] != ''){
            $rnd = time().rand(10,99);
            $uploadedFile = CUploadedFile::getInstance($model,'MenuImage');
            $fileName = $rnd.".".$uploadedFile->extensionName; 
            $model->MenuImage = $fileName;
         }
         
         if($model->validate()){
            if($model->save()){
               if($_FILES['Menuadmin']['name']['MenuImage'] != ''){
                  $pathImage = Yii::getPathOfAlias("webroot").'/images/menu/'.$fileName;
                  $uploadedFile->saveAs($pathImage);  // image will uplode to rootDirectory/banner/
                  
                  //resize image
                  $image = new SimpleImage();
                  $image->load($pathImage);
                  $image->resizeToWidth(200);
                  $image->save($pathImage);  
               }
               
               
               $message = 'Cập nhật thành công';
               
            }
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      }
      
      $attrbutes_level_1[] = array("menu" => '0');
      $attrbutes_level_2[] = array("menu" => '0');
      $attrbutes_level_3[] = array("menu" => '0');
      $attrbutes_level_4[] = array("menu" => '0');
      $menu_level_1 = array(0 => '-- Nhóm 1 --');
      $menu_level_2 = array(0 => '-- Nhóm 2 --');
      $menu_level_3 = array(0 => '-- Nhóm 3 --');
      $menu_level_4 = array(0 => '-- Nhóm 4 --');
      if($id > 0){
         
         $level = $model->getLevel($id);
         $id_parent_max = $model->getIdParentMax($id);
         $all_level_1 = $model->getMenuByLevel(1);
         //var_dump($id_parent_max);die();
         if($id_parent_max > 0){
            $all_child = $model->getChild($id_parent_max);
            
            $model->attributes =  $model->findByPk($id)->attributes;
            
            foreach($all_level_1 as $item){
               $menu_level_1 [$item['Menu1']] = $item['MenuName'];
               $attrbutes_level_1[] = array("menu" => $item['MenuAdminID']);
            }
            if(isset($all_child[2])){
               foreach($all_child[2] as $item){
                  $menu_level_2[$item['Menu2']] = $item['MenuName'];
                  $attrbutes_level_2[] = array("menu" => $item['MenuAdminID']);
               }
            }
            if(isset($all_child[3])){
               foreach($all_child[3] as $item){
                  $menu_level_3[$item['Menu3']] = $item['MenuName'];
                  $attrbutes_level_3[] = array("menu" => $item['MenuAdminID']);
               }
            }
            
            $menu_parent = $model->getParent($id);
         }
         
      }else{
         $this->redirect(CController::createUrl('/admin/menu/'));
      }
      $this->layout ='//layouts/cms/create';
      $this->pageTitle = 'Cập nhật module';
      $this->render('edit',array('model' => $model,
                                 'session_user' => $session_user,
                                 'menu_level_1' => $menu_level_1,
                                 'menu_level_2' => $menu_level_2,
                                 'menu_level_3' => $menu_level_3,
                                 'menu_level_4' => $menu_level_4,
                                 'attrbutes_level_1' => $attrbutes_level_1,
                                 'attrbutes_level_2' => $attrbutes_level_2,
                                 'attrbutes_level_3' => $attrbutes_level_3,
                                 'attrbutes_level_4' => $attrbutes_level_4));
      
   }
   
   /**
    * Deactive record
   */
	public function actionDeactive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == $_SESSION['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE menuadmin SET IsActive = 0 WHERE MenuAdminID IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Active record
   */
	public function actionActive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == $_SESSION['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE menuadmin SET IsActive = 1 WHERE MenuAdminID IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == $_SESSION['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM menuadmin WHERE MenuAdminID IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Return option menu level 2 for creat action
   */
   public function actionLoadMenu2(){
      $menu = Yii::app()->request->getParam('menu',0);
      echo '<option value="0" menu="0">-- Nhóm 2 --</option>';
      if($menu != 0){
         $sql =  "SELECT
                  	a.*
                  FROM
                  	menuadmin a
                  INNER JOIN (
                  	SELECT
                  		MenuAdminID,Menu1,Menu2,Menu3,Menu4
                  	FROM
                  		menuadmin c
                  	WHERE
                  		MenuAdminID = $menu
                  ) b ON (
                  	b.Menu1 = a.Menu1
                  	AND b.Menu1 > 0
                  	AND b.Menu2 = 0
                  	AND a.Menu3 = 0
                  )
                  WHERE
                  	a.IsActive = 1
                  AND a.MenuAdminID != $menu";
         $db = Yii::app()->db;
         $cmd = $db->createCommand($sql);
         $result = $cmd->queryAll();
         if(count($result) > 0){
            foreach($result  as $item){
               echo '<option value="'.$item['Menu2'].'" menu="'.$item['MenuAdminID'].'">'.$item['MenuName'].'</option>';
            }
         }
      }
   }
   
   /**
    * Return option menu level 2 for index action
   */
   public function actionLoadMenu2Index(){
      $menu = Yii::app()->request->getParam('menu',0);
      echo '<option value="0">-- Nhóm 2 --</option>';
      if($menu != 0){
         $sql =  "SELECT
                  	a.*
                  FROM
                  	menuadmin a
                  INNER JOIN (
                  	SELECT
                  		MenuAdminID,Menu1,Menu2,Menu3,Menu4
                  	FROM
                  		menuadmin c
                  	WHERE
                  		MenuAdminID = $menu
                  ) b ON (
                  	b.Menu1 = a.Menu1
                  	AND b.Menu1 > 0
                  	AND b.Menu2 = 0
                  	AND a.Menu3 = 0
                  )
                  WHERE
                  	a.IsActive = 1
                  AND a.MenuAdminID != $menu";
         $db = Yii::app()->db;
         $cmd = $db->createCommand($sql);
         $result = $cmd->queryAll();
         if(count($result) > 0){
            foreach($result  as $item){
               echo '<option value="'.$item['MenuAdminID'].'">'.$item['MenuName'].'</option>';
            }
         }
      }
   }
   
   /**
    * Return option menu level 3
   */
   public function actionloadMenu3(){
      $menu = Yii::app()->request->getParam('menu',0);
      echo '<option value="0" menu="0">-- Nhóm 3 --</option>';
      if($menu != 0){
         $sql =  "SELECT
                  	a.*
                  FROM
                  	menuadmin a
                  INNER JOIN (
                  	SELECT
                  		MenuAdminID,Menu1,Menu2,Menu3,Menu4
                  	FROM
                  		menuadmin c
                  	WHERE
                  		MenuAdminID = $menu
                  ) b ON (
                  	b.Menu1 = a.Menu1
                     AND b.Menu2 = a.Menu2
                  	AND b.Menu1 > 0
                  	AND b.Menu2 > 0
                  	AND a.Menu3 > 0
                     AND a.Menu4 = 0
                  )
                  WHERE
                  	a.IsActive = 1
                  AND a.MenuAdminID != $menu";
         $db = Yii::app()->db;
         $cmd = $db->createCommand($sql);
         $result = $cmd->queryAll();
         if(count($result) > 0){
            foreach($result  as $item){
               echo '<option value="'.$item['Menu3'].'" menu="'.$item['MenuAdminID'].'">'.$item['MenuName'].'</option>';
            }
         }
      }
   }	
   /*
	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}